<template>
  <div class="p-2">
    <Card class="mb-[12px] filter-card">
      <Form
        ref="queryFormRef"
        :model="queryParams"
        layout="inline"
        class="filter-form"
        :label-col="{ style: { width: '90px' } }"
      >
        <div class="filter-row">
          <FormItem class="filter-item" label="客户服务站" name="serviceStation">
            <Select
              v-model:value="queryParams.serviceStation"
              placeholder="请选择客户服务站"
              allow-clear
              show-search
              :filter-option="filterSelectOption"
            >
              <SelectOption v-for="item in dropdownOptions.serviceStation" :key="item" :value="item">
                {{ item }}
              </SelectOption>
            </Select>
          </FormItem>
          <FormItem class="filter-item" label="零售户" name="retailCustomer">
            <Select
              v-model:value="queryParams.retailCustomer"
              placeholder="请选择零售户"
              allow-clear
              show-search
              :filter-option="filterSelectOption"
            >
              <SelectOption v-for="item in dropdownOptions.retailCustomer" :key="item" :value="item">
                {{ item }}
              </SelectOption>
            </Select>
          </FormItem>
          <FormItem class="filter-item" label="商品档位" name="productGrade">
            <Select
              v-model:value="queryParams.productGrade"
              placeholder="请选择商品档位"
              allow-clear
              show-search
              :filter-option="filterSelectOption"
            >
              <SelectOption v-for="item in dropdownOptions.productGrade" :key="item" :value="item">
                {{ item }}
              </SelectOption>
            </Select>
          </FormItem>
          <FormItem class="filter-item" label="商品价类" name="productPriceType">
            <Select
              v-model:value="queryParams.productPriceType"
              placeholder="请选择商品价类"
              allow-clear
              show-search
              :filter-option="filterSelectOption"
            >
              <SelectOption v-for="item in dropdownOptions.productPriceType" :key="item" :value="item">
                {{ item }}
              </SelectOption>
            </Select>
          </FormItem>
          <FormItem class="filter-item" label="商品名称" name="productName">
            <Select
              v-model:value="queryParams.productName"
              placeholder="请选择商品"
              allow-clear
              show-search
              :filter-option="filterSelectOption"
            >
              <SelectOption v-for="item in dropdownOptions.productName" :key="item" :value="item">
                {{ item }}
              </SelectOption>
            </Select>
          </FormItem>
        </div>
        <div class="filter-actions-row">
          <Button class="search-btn" type="primary" @click="handleQuery">预测</Button>
          <Button class="reset-btn" @click="resetQuery">重置</Button>
        </div>
      </Form>
    </Card>

    <Card>
      <template #title>
        <Row :gutter="10" class="mb8" style="margin-bottom: 0">
          <Col :span="1.5">
            <Button type="default" @click="handleExport" v-access:code="['data:table:export']">导出</Button>
          </Col>
        </Row>
      </template>

      <Table
        :loading="loading"
        :dataSource="tableList"
        :columns="columns"
        :pagination="false"
        :row-key="(_record: any, index?: number) => index ?? 0"
        :scroll="{ x: 'max-content' }"
      >
        <template #bodyCell="{ column }">
          <template v-if="column.key === 'action'">
            <Space>
              
            </Space>
          </template>
        </template>
      </Table>

      <Pagination
        v-show="total > 0"
        :total="total"
        :current="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        show-size-changer
        :show-total="(total: number) => `共 ${total} 条`"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
        style="margin-top: 16px; text-align: right"
      />
    </Card>

    <!-- 添加或修改数据对话框
    <Modal
      :title="dialog.title"
      v-model:open="dialog.visible"
      width="500px"
      :confirm-loading="buttonLoading"
      @ok="submitForm"
      @cancel="cancel"
    >
      <Form ref="tableFormRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <FormItem label="编号" name="dataCode">
          <Input v-model:value="form.dataCode" placeholder="请输入编号" />
        </FormItem>
        <FormItem label="表名" name="dataTable">
          <Input v-model:value="form.dataTable" placeholder="请输入表名" />
        </FormItem>
        <FormItem label="表中文名" name="dataTableName">
          <Input v-model:value="form.dataTableName" placeholder="请输入表中文名" />
        </FormItem>
        <FormItem label="SQL语句" name="dataSql">
          <Input.TextArea v-model:value="form.dataSql" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="规则公式" name="dataFormula">
          <Input.TextArea v-model:value="form.dataFormula" placeholder="请输入内容" :rows="4" />
        </FormItem>
        <FormItem label="备注" name="remark">
          <Input.TextArea v-model:value="form.remark" placeholder="请输入内容" :rows="4" />
        </FormItem>
      </Form>
    </Modal> -->
  </div>
</template>

<script setup name="Table" lang="ts">
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import {
  Card,
  Form,
  FormItem,
  Button,
  Table,
  Pagination,
  Row,
  Col,
  Space,
  Select,
  SelectOption,
  message,
} from 'ant-design-vue';
import { listTable } from '#/api/operate/daySalesDetail/show';
import type { TableVO, TableQuery, TableForm } from '#/api/operate/daySalesDetail/showTypes';

const tableList = ref<TableVO[]>([]);
const rawDataList = ref<TableVO[]>([]);
const allDataList = ref<TableVO[]>([]); // 存储筛选后的数据用于客户端分页
const loading = ref(true);
const total = ref(0);
const queryFormRef = ref();

const dropdownOptions = reactive<{
  serviceStation: string[];
  retailCustomer: string[];
  productGrade: string[];
  productPriceType: string[];
  productName: string[];
}>({
  serviceStation: [],
  retailCustomer: [],
  productGrade: [],
  productPriceType: [],
  productName: [],
});

const formatDate = (value?: string | number | null) => {
  if (!value) return '-';
  const str = String(value);
  if (str.length >= 10) {
    return str.substring(0, 10);
  }
  return str;
};

const columns = [
  {
    title: '订货日期',
    dataIndex: 'md04_order_date',
    key: 'md04_order_date',
    align: 'center' as const,
    customRender: ({ text }: { text: string }) => formatDate(text),
  },
  {
    title: '记账日期',
    dataIndex: 'md04_pose_date',
    key: 'md04_pose_date',
    align: 'center' as const,
    customRender: ({ text }: { text: string }) => formatDate(text),
  },
  {
    title: '零售户代码',
    dataIndex: 'bb_retail_customer_code',
    key: 'bb_retail_customer_code',
    align: 'center' as const,
  },
  {
    title: '零售户名称',
    dataIndex: 'bb_retail_customer_name',
    key: 'bb_retail_customer_name',
    align: 'center' as const,
  },
  {
    title: '地市级公司简称',
    dataIndex: 'ba_city_org_short_name',
    key: 'ba_city_org_short_name',
    align: 'center' as const,
  },
  {
    title: '客户服务站',
    dataIndex: 'md04_serv_station_name',
    key: 'md04_serv_station_name',
    align: 'center' as const,
  },
  {
    title: '商品代码',
    dataIndex: 'md05_product_code',
    key: 'md05_product_code',
    align: 'center' as const,
  },
  {
    title: '商品名称',
    dataIndex: 'md05_product_name',
    key: 'md05_product_name',
    align: 'center' as const,
  },
  {
    title: '商品价类名称',
    dataIndex: 'md05_product_pr_type_name',
    key: 'md05_product_pr_type_name',
    align: 'center' as const,
  },
  {
    title: '商品档位名称',
    dataIndex: 'md05_product_grade_name',
    key: 'md05_product_grade_name',
    align: 'center' as const,
  },
  {
    title: '商品批发价',
    dataIndex: 'md05_product_trade_price',
    key: 'md05_product_trade_price',
    align: 'center' as const,
  },
  {
    title: '商品零售指导价',
    dataIndex: 'md05_product_rtl_guide_price',
    key: 'md05_product_rtl_guide_price',
    align: 'center' as const,
  },
  {
    title: '商品订购含税金额',
    dataIndex: 'md05_product_order_withtax_amt',
    key: 'md05_product_order_withtax_amt',
    align: 'center' as const,
  },
  {
    title: '商品不含税金额',
    dataIndex: 'md02_product_no_tax_amt',
    key: 'md02_product_no_tax_amt',
    align: 'center' as const,
  },
  {
    title: '商品要货金额',
    dataIndex: 'md04_product_req_amt',
    key: 'md04_product_req_amt',
    align: 'center' as const,
  },
  {
    title: '商品税额',
    dataIndex: 'md02_product_tax_amt',
    key: 'md02_product_tax_amt',
    align: 'center' as const,
  },
  {
    title: '商品条订购量',
    dataIndex: 'md05_product_order_strips_qty',
    key: 'md05_product_order_strips_qty',
    align: 'center' as const,
  },
  {
    title: '商品支订购量',
    dataIndex: 'md04_product_order_branch_qty',
    key: 'md04_product_order_branch_qty',
    align: 'center' as const,
  },
  {
    title: '商品要货数量',
    dataIndex: 'md04_product_req_qty',
    key: 'md04_product_req_qty',
    align: 'center' as const,
  },
  {
    title: '商品支要货数量',
    dataIndex: 'md04_product_req_branch_qty',
    key: 'md04_product_req_branch_qty',
    align: 'center' as const,
  },
  {
    title: '商品订货合理定量',
    dataIndex: 'md04_product_order_rsn_qty',
    key: 'md04_product_order_rsn_qty',
    align: 'center' as const,
  },
  {
    title: '商品订货支合理定量',
    dataIndex: 'md04_product_order_branch_rsn_qty',
    key: 'md04_product_order_branch_rsn_qty',
    align: 'center' as const,
  }
];

const initFormData: TableForm = {
  md04_com_rtl_order_detail_no: undefined,
  md04_order_date: undefined,
  md04_pose_date: undefined,
  bb_retail_customer_code: undefined,
  bb_retail_customer_name: undefined,
  ba_city_org_short_name: undefined,
  md04_serv_station_name: undefined,
  md05_product_code: undefined,
  md05_product_name: undefined,
  md05_product_pr_type_name: undefined,
  md05_product_grade_name: undefined,
  md05_product_trade_price: undefined,
  md05_product_rtl_guide_price: undefined,
  md05_product_order_withtax_amt: undefined,
  md02_product_no_tax_amt: undefined,
  md04_product_req_amt: undefined,
  md02_product_tax_amt: undefined,
  md05_product_order_strips_qty: undefined,
  md04_product_order_branch_qty: undefined,
  md04_product_req_qty: undefined,
  md04_product_req_branch_qty: undefined,
  md04_product_order_rsn_qty: undefined,
  md04_product_order_branch_rsn_qty: undefined
};

const data = reactive<{
  form: TableForm;
  queryParams: TableQuery & {
    pageNum: number;
    pageSize: number;
    serviceStation?: string;
    retailCustomer?: string;
    productGrade?: string;
    productPriceType?: string;
    productName?: string;
  };
  rules: Record<string, any[]>;
}>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dataCode: undefined,
    userId: undefined,
    param: {},
    year: undefined,
    month: undefined,
    serviceStation: undefined,
    retailCustomer: undefined,
    productGrade: undefined,
    productPriceType: undefined,
    productName: undefined,
  },
  rules: {
    dataCode: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
    dataTable: [{ required: true, message: '表名不能为空', trigger: 'blur' }],
    dataTableName: [{ required: true, message: '表中文名不能为空', trigger: 'blur' }],
  },
});

const { queryParams } = toRefs(data);

const filterSelectOption = (input: string, option?: any) => {
  const text = option?.value ?? '';
  return text?.toString().toLowerCase().includes(input.toLowerCase());
};

const generateOptionList = (source: any[], key: string) => {
  const set = new Set<string>();
  source.forEach((item) => {
    if (item[key]) {
      set.add(item[key]);
    }
  });
  return Array.from(set).sort((a, b) => a.localeCompare(b, 'zh-CN'));
};

const updateDropdownOptions = () => {
  dropdownOptions.serviceStation = generateOptionList(
    applyFilters(rawDataList.value, 'serviceStation'),
    'md04_serv_station_name',
  );
  dropdownOptions.retailCustomer = generateOptionList(
    applyFilters(rawDataList.value, 'retailCustomer'),
    'bb_retail_customer_name',
  );
  dropdownOptions.productGrade = generateOptionList(
    applyFilters(rawDataList.value, 'productGrade'),
    'md05_product_grade_name',
  );
  dropdownOptions.productPriceType = generateOptionList(
    applyFilters(rawDataList.value, 'productPriceType'),
    'md05_product_pr_type_name',
  );
  dropdownOptions.productName = generateOptionList(
    applyFilters(rawDataList.value, 'productName'),
    'md05_product_name',
  );
};

/** 根据输入条件过滤数据 */
const applyFilters = (list: any[], excludeField?: string) => {
  let dataList = list;
  const {
    serviceStation,
    retailCustomer,
    productGrade,
    productPriceType,
    productName,
  } = queryParams.value;

  if (excludeField !== 'serviceStation' && serviceStation && serviceStation.trim()) {
    const keyword = serviceStation.trim();
    dataList = dataList.filter((item: any) =>
      (item.md04_serv_station_name || '').includes(keyword),
    );
  }
  if (excludeField !== 'retailCustomer' && retailCustomer && retailCustomer.trim()) {
    const keyword = retailCustomer.trim();
    dataList = dataList.filter((item: any) =>
      (item.bb_retail_customer_name || '').includes(keyword),
    );
  }
  if (excludeField !== 'productGrade' && productGrade && productGrade.trim()) {
    const keyword = productGrade.trim();
    dataList = dataList.filter((item: any) =>
      (item.md05_product_grade_name || '').includes(keyword),
    );
  }
  if (
    excludeField !== 'productPriceType' &&
    productPriceType &&
    productPriceType.trim()
  ) {
    const keyword = productPriceType.trim();
    dataList = dataList.filter((item: any) =>
      (item.md05_product_pr_type_name || '').includes(keyword),
    );
  }
  if (excludeField !== 'productName' && productName && productName.trim()) {
    const keyword = productName.trim();
    dataList = dataList.filter((item: any) =>
      (item.md05_product_name || '').includes(keyword),
    );
  }

  return dataList;
};

/** 更新表格显示数据(客户端分页) */
const updateTableList = () => {
  const startIndex = (queryParams.value.pageNum - 1) * queryParams.value.pageSize;
  const endIndex = startIndex + queryParams.value.pageSize;
  tableList.value = allDataList.value.slice(startIndex, endIndex);
};

const hasActiveFilter = () => {
  const { serviceStation, retailCustomer, productGrade, productPriceType, productName } =
    queryParams.value;
  return !!(
    serviceStation?.trim() ||
    retailCustomer?.trim() ||
    productGrade?.trim() ||
    productPriceType?.trim() ||
    productName?.trim()
  );
};

/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listTable(queryParams.value);
    console.log('API 返回数据:', res);

    // 根据后端实际返回的数据结构处理
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      // 如果直接返回数组
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      // 如果返回的是 { rows: [...], total: number } 结构
      dataList = res.rows;
    } else {
      console.warn('未知的数据结构:', res);
      dataList = [];
    }

    rawDataList.value = dataList;
    // 更新下拉选项
    updateDropdownOptions();

    if (hasActiveFilter()) {
      dataList = applyFilters(dataList);
    }

    // 按档位顺序排序
    const gradeOrder = ['一档', '二档', '三档', '四档', '五档', '六档', '七档', '八档', '九档', '十档'];
    dataList.sort((a: any, b: any) => {
      const gradeA = a.md05_product_grade_name || '';
      const gradeB = b.md05_product_grade_name || '';
      const indexA = gradeOrder.indexOf(gradeA);
      const indexB = gradeOrder.indexOf(gradeB);
      
      // 如果都在预定义列表中,按预定义顺序排序
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      // 如果只有一个在预定义列表中,在列表中的排前面
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      // 如果都不在预定义列表中,按字母顺序排序
      return gradeA.localeCompare(gradeB, 'zh-CN');
    });
    
    // 保存全量数据用于分页
    allDataList.value = dataList;
    total.value = dataList.length;
    
    // 客户端分页
    updateTableList();
    
    console.log('处理后的表格数据:', tableList.value);
    console.log('数据总数:', total.value);
  } catch (error) {
    console.error('获取数据失败:', error);
    tableList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

/** 导出按钮操作 */
const handleExport = async () => {
  const hideLoading = message.loading('正在导出数据...', 0);
  
  try {
    // 获取当前筛选后的数据
    const res = await listTable(queryParams.value);
    
    let dataList: any[] = [];
    if (Array.isArray(res)) {
      dataList = res;
    } else if (res && 'rows' in res && Array.isArray(res.rows)) {
      dataList = res.rows;
    }

    if (hasActiveFilter()) {
      dataList = applyFilters(dataList);
    }

    // 检查是否有数据
    if (dataList.length === 0) {
      message.warning('当前筛选条件下没有数据可导出');
      return;
    }
    
    // 按档位顺序排序
    const gradeOrder = ['一档', '二档', '三档', '四档', '五档', '六档', '七档', '八档', '九档', '十档'];
    dataList.sort((a: any, b: any) => {
      const gradeA = a.md05_product_grade_name || '';
      const gradeB = b.md05_product_grade_name || '';
      const indexA = gradeOrder.indexOf(gradeA);
      const indexB = gradeOrder.indexOf(gradeB);
      
      if (indexA !== -1 && indexB !== -1) {
        return indexA - indexB;
      }
      if (indexA !== -1) return -1;
      if (indexB !== -1) return 1;
      return gradeA.localeCompare(gradeB, 'zh-CN');
    });

    const exportableColumns = columns.filter((col) => Boolean(col.dataIndex));
    const headers = exportableColumns.map((col) => col.title as string);
    const csvContent = [
      headers.join(','),
      ...dataList.map((item: any) =>
        exportableColumns
          .map((col) => {
            const value = item[col.dataIndex as keyof typeof item];
            if (value === null || value === undefined) return '';
            const str = String(value);
            if (str.includes(',') || str.includes('\n') || str.includes('"')) {
              return `"${str.replace(/"/g, '""')}"`;
            }
            return str;
          })
          .join(','),
      ),
    ].join('\n');
    
    // 添加BOM头以支持中文
    const BOM = '\uFEFF';
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' });
    
    // 构建文件名
    const fileName = `年度需求销售额_${new Date().getTime()}.csv`;
    
    // 创建下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', fileName);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    message.success(`导出成功! 共导出 ${dataList.length} 条数据`);
  } catch (error) {
    console.error('导出失败:', error);
    message.error('导出失败');
  } finally {
    hideLoading();
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 分页变化 */
const handlePageChange = (page: number) => {
  queryParams.value.pageNum = page;
  updateTableList(); // 使用客户端分页,无需重新请求
};

/** 分页大小变化 */
const handlePageSizeChange = (_current: number, size: number) => {
  queryParams.value.pageSize = size;
  queryParams.value.pageNum = 1;
  updateTableList(); // 使用客户端分页,无需重新请求
};

onMounted(() => {
  getList();
});

watch(
  () => [
    queryParams.value.serviceStation,
    queryParams.value.retailCustomer,
    queryParams.value.productGrade,
    queryParams.value.productPriceType,
    queryParams.value.productName,
  ],
  () => {
    updateDropdownOptions();
  },
);
</script>

<style scoped>
.filter-card {
  border-radius: 16px;
  border: 1px solid #eef2f6;
  box-shadow: 0 6px 24px rgba(15, 23, 42, 0.06);
  background: linear-gradient(135deg, #ffffff 0%, #f7f9ff 100%);
}

.filter-form {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px 24px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.filter-item :deep(.ant-form-item-label) {
  padding: 0 8px 0 0;
}

.filter-item :deep(.ant-select),
.filter-item :deep(.ant-select-selector),
.filter-item :deep(.ant-input) {
  width: 180px;
  border-radius: 6px !important;
}

.filter-item :deep(.ant-form-item-label > label) {
  font-weight: normal;
  color: #666;
  font-size: 14px;
}

.filter-actions-row {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.filter-actions-row :deep(.ant-btn) {
  min-width: 80px;
  height: 34px;
  border-radius: 18px;
  font-size: 14px;
  padding: 4px 18px;
}

.search-btn {
  background: #1677ff;
  border: none;
  box-shadow: none;
}

.reset-btn {
  border-color: #d9d9d9;
  color: #5c667a;
  background: #fff;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
